package com.smiier.skin.ui;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import cn.o.app.net.INetTask;
import cn.o.app.net.NetTaskListener;
import cn.o.app.qrcode.QRCodeView;
import cn.o.app.ui.ODialog;
import cn.o.app.ui.OImageView;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.lidroid.xutils.BitmapUtils;
import com.smiier.skin.AccountActivity;
import com.smiier.skin.DoctorDetailActivity;
import com.smiier.skin.MyFollowingDoctorActivity;
import com.smiier.skin.MyFollowingQuestionActivity;
import com.smiier.skin.MyQuestionDetailActivity;
import com.smiier.skin.MyTreatmentProjectListActivity;
import com.smiier.skin.PatientProfileEditActivity;
import com.smiier.skin.QuestionDetailActivity;
import com.smiier.skin.ScanActivity;
import com.smiier.skin.SystemActivity;
import com.smiier.skin.TipMessageActivity;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.net.AccountGetTask;
import com.smiier.skin.net.AccountGetTask.AccountGetRequest;
import com.smiier.skin.net.AccountGetTask.AccountGetResponse;
import com.smiier.skin.net.CounterGetTask;
import com.smiier.skin.net.CounterGetTask.CounterGetRequest;
import com.smiier.skin.net.CounterGetTask.CounterGetResponse;
import com.smiier.skin.net.CounterGetTask.TypeCount;
import com.smiier.skin.net.CounterGetTask.ValueCount;
import com.smiier.skin.net.DoctorReserveListTask;
import com.smiier.skin.net.DoctorReserveListTask.DoctorReserveListRequest;
import com.smiier.skin.net.DoctorReserveListTask.DoctorReserveListResponse;
import com.smiier.skin.net.RelationshipGetListTask;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListRequest;
import com.smiier.skin.net.RelationshipGetListTask.RelationshipGetListResponse;
import com.smiier.skin.util.GlobalFormat;
import com.smiier.skin.util.GlobalSettings;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.DBUtil;
import com.smiier.skin.vo.TipMessageVo;

public class PersonalPatientView extends BasicStateView implements
		View.OnClickListener {

	protected View rl_profile;
	protected View mYueView;
	protected View mTipMsgView;
	protected View mMyQuestionView;
	protected View mMyGuanZhuView;
	protected View mSystemSettingView;
	private TextView mShouCangValue;
	private TextView text_patient_name;
	protected TextView text_patient_id;
	protected TextView text_patient_guanzhu_num;
	protected TextView text_yue_value;
	protected TextView text_my_question_value;
	protected TextView text_my_guanzhu_value;
	private ODialog mVarcardDialog;
	private OImageView img_patient_icon;
	private View mShouCang;
	protected View view_doctor_qr;
	private TextView mDoctorNumber;
	private RelativeLayout mDoctorView;
	protected BitmapUtils mBitmapUtils;
	private RelativeLayout mAddDoctor;
	private TextView mNotifyNumber;
	RelativeLayout mMyProject;
	TextView mMyProjectNum;
	TextView mNotifyNum;

	public PersonalPatientView(Context context) {
		super(context);
	}

	public PersonalPatientView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public PersonalPatientView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	@Override
	public void onCreate() {
		super.onCreate();

		Log.i("testmessage", "personalPatien.onCreate");

		setContentView(R.layout.view_personal_patient);
		mVarcardDialog = new ODialog(getContext());
		mVarcardDialog.setWindowAnimations(R.style.DialogFromTopAnim);
		mBitmapUtils = new BitmapUtils(getContext());

		init();
		setNavTitle("我的");
		setNavRightBtnIcon(R.drawable.ic_vcard);
		back.setVisibility(View.GONE);
		back.setOnClickListener(this);
		text_right.setOnClickListener(this);

		rl_profile = findViewById(R.id.rl_profile, View.class);
		if (rl_profile != null) {
			rl_profile.setOnClickListener(this);
		}
		mMyProject = findViewById(R.id.view_my_project, RelativeLayout.class);
		mNotifyNum = findViewById(R.id.text_tip_msg_num, TextView.class);
		mMyProject.setOnClickListener(this);
		mYueView = findViewById(R.id.view_yue, View.class);
		if (mYueView != null) {
			mYueView.setOnClickListener(this);
		}
		mTipMsgView = findViewById(R.id.view_tip_msg, View.class);
		if (mTipMsgView != null) {
			mTipMsgView.setOnClickListener(this);
		}
		mMyQuestionView = findViewById(R.id.view_my_question, View.class);
		if (mMyQuestionView != null) {
			mMyQuestionView.setOnClickListener(this);
		}
		mMyProjectNum = findViewById(R.id.text_my_project_value, TextView.class);
		mShouCangValue = (TextView) findViewById(R.id.text_my_shoucang_value);
		mMyGuanZhuView = findViewById(R.id.view_my_guanzhu, View.class);
		if (mMyGuanZhuView != null) {
			mMyGuanZhuView.setOnClickListener(this);
		}
		mShouCang = this.findViewById(R.id.view_my_shoucang, View.class);
		if (mShouCang != null) {
			mShouCang.setOnClickListener(this);
		}
		mSystemSettingView = findViewById(R.id.view_system_setting, View.class);
		if (mSystemSettingView != null) {
			mSystemSettingView.setOnClickListener(this);
		}

		text_patient_name = findViewById(R.id.text_patient_name, TextView.class);
		text_patient_id = findViewById(R.id.text_patient_id, TextView.class);

		Log.i("testnew", "PesronalPatientView:mMessage");
		text_patient_guanzhu_num = findViewById(R.id.text_patient_guanzhu_num,
				TextView.class);
		text_yue_value = findViewById(R.id.text_yue_value, TextView.class);
		text_my_question_value = findViewById(R.id.text_my_question_value,
				TextView.class);
		text_my_guanzhu_value = findViewById(R.id.text_my_guanzhu_value,
				TextView.class);
		img_patient_icon = findViewById(R.id.img_patient_icon, OImageView.class);
		mDoctorNumber = findViewById(R.id.text_my_doctor_value, TextView.class);
		mDoctorView = findViewById(R.id.view_my_doctor, RelativeLayout.class);
		// mNotifyNumber = findViewById(R.id.text_tip_msg_num, TextView.class);
		mAddDoctor = findViewById(R.id.add_doctor, RelativeLayout.class);
		mAddDoctor.setOnClickListener(this);
		mDoctorView.setOnClickListener(this);
		img_patient_icon.setOnClickListener(this);

		IntentFilter noReadTab = new IntentFilter(
				Constant.RECIVER_MYIFNO_ITEM_NOREAD);
		getContext().registerReceiver(noReadTabReceiver, noReadTab);

		initMessageNoRead();
	}

	BroadcastReceiver noReadTabReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			initMessageNoRead();
		}
	};

	private void initMessageNoRead() {

		DBUtil dbUtil = null;
		if (dbUtil == null) {
			dbUtil = DBUtil.getInstance(getContext());
		}

		ArrayList<TipMessageVo> list = dbUtil.query(TipMessageVo.class);

		int noReadNumber = 0;

		if (!list.isEmpty()) {
			for (int i = 0; i < list.size(); i++) {

				if (list.get(i).readState == 0) {
					noReadNumber++;
				}
			}
		}

		if (noReadNumber > 0) {
			mNotifyNum.setText(noReadNumber + "");
			// mNotifyNum.setBackgroundResource(R.drawable.no_read_point);
		} else {
			mNotifyNum.setText("");
			// mNotifyNum.setBackgroundResource(0);
		}

	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		// if (noReadTabReceiver != null) {
		// getContext().unregisterReceiver(noReadTabReceiver);
		// }
	}

	@Override
	public boolean onInterceptBackPressed() {
		if (CommonUtility.indexOf((Activity) getContext(), view_doctor_qr) != -1) {
			CommonUtility.removeView((Activity) getContext(), view_doctor_qr,
					R.anim.push_up_out_activity);
			return true;
		}
		return super.onInterceptBackPressed();
	}

	public void onResume() {
		super.onResume();
		if (CommonUtility.isNull(GlobalSettings.sUser)) {
			return;
		}
		/*
		 * ArrayList<TipMessageVo> list = dbUtil.query(TipMessageVo.class); if
		 * (list != null) { mNotifyNum.setText(list.size() + ""); }
		 */
		if (!CommonUtility.isNull(GlobalSettings.sUser)) {
			try {
				text_patient_name.setText(GlobalSettings.sUser.Name);
				StringBuilder sb = new StringBuilder();
				sb.append(CommonUtility.sex.get(GlobalSettings.sUser.Sex))
						.append("，")
						.append(CommonUtility
								.getAgeByBirthday(GlobalSettings.sUser.Birth
										.toString())).append("岁");
				// .append("，")
				// .append(GlobalSettings.sUser.Nation)
				// .append("，")
				// .append(CommonUtility.marry
				// .get(GlobalSettings.sUser.Marital_Status))
				// .append("，")
				// .append("现居" + GlobalSettings.sUser.Province);
				text_patient_id.setText(sb.toString());

				/*
				 * mBitmapUtils.display(img_patient_icon,
				 * GlobalSettings.SERVER_IMG_URL + GlobalSettings.sUser.Pic +
				 * Constant.IMG_SRC, new OBitmapLoadCallBack<View>());
				 */
				CommonUtility.displayHeadImage(img_patient_icon, mBitmapUtils,
						GlobalSettings.SERVER_IMG_URL
								+ GlobalSettings.sUser.Pic + Constant.IMG_TH,
						getContext().getResources(), GlobalSettings.sUser.Sex);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		AccountGetRequest req = new AccountGetRequest();
		req.token = GlobalSettings.sToken;
		AccountGetTask task = new AccountGetTask();
		task.setRequest(req);
		task.addListener(new NetTaskListener<AccountGetTask.AccountGetRequest, AccountGetTask.AccountGetResponse>() {

			@Override
			public void onException(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					Exception e) {

			}

			@Override
			public void onComplete(
					INetTask<AccountGetRequest, AccountGetResponse> task,
					AccountGetResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				GlobalSettings.sYue = response.Res;
				String totalAccount = GlobalFormat
						.formatCNY(GlobalSettings.sYue);
				text_yue_value.setText(totalAccount + "元");
			}
		});
		add(task);

		// 获取问题，悬赏和关注数量
		CounterGetRequest cReq = new CounterGetRequest();
		cReq.types = new ArrayList<Integer>();
		cReq.types.add(1001);
		cReq.types.add(1002);
		cReq.types.add(2007);
		cReq.types.add(2005);
		cReq.types.add(2006);
		cReq.types.add(1004);
		cReq.uids = new ArrayList<Long>();
		cReq.uids.add(GlobalSettings.sUid);
		CounterGetTask cTask = new CounterGetTask();
		cTask.setRequest(cReq);
		cTask.addListener(new NetTaskListener<CounterGetTask.CounterGetRequest, CounterGetTask.CounterGetResponse>() {

			@Override
			public void onException(
					INetTask<CounterGetRequest, CounterGetResponse> task,
					Exception e) {
			}

			@Override
			public void onComplete(
					INetTask<CounterGetRequest, CounterGetResponse> task,
					CounterGetResponse response) {
				if (response.ResultCode != 200) {
					return;
				}
				try {
					ArrayList<TypeCount> Res = response.Res;
					int guanzhu_num = 0;
					String[] guanzhu_num_intent = new String[2];
					for (int i = 0; i < Res.size(); i++) {
						TypeCount type = Res.get(i);
						if (type.Value.size() > 0) {
							ValueCount count = type.Value.get(0);
							long key = type.Key;

							if (key == 1001) {
								text_my_question_value
										.setText(count.Value + "");
							} else if (key == 1002) {
								mShouCangValue.setText(count.Value + "");
								guanzhu_num_intent[0] = count.Value + "";
							} else if (key == 2007) {
								guanzhu_num += count.Value;
								guanzhu_num_intent[1] = count.Value + "";
								// mDoctorNumber.setText(count.Value + "");
							} else if (key == 2006) {
								// guanzhu_num += count.Value;
							}
						}
					}
					text_my_guanzhu_value.setText(guanzhu_num + "");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
		add(cTask);
		RelationshipGetListTask rtask = new RelationshipGetListTask();
		RelationshipGetListRequest rreq = new RelationshipGetListRequest();
		rreq.token = GlobalSettings.sToken;
		rtask.setRequest(rreq);
		rtask.addListener(new NetTaskListener<RelationshipGetListTask.RelationshipGetListRequest, RelationshipGetListTask.RelationshipGetListResponse>() {

			@Override
			public void onComplete(
					INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
					RelationshipGetListResponse response) {
				if (response != null && response.ResultCode == 200) {
					mDoctorNumber.setText(response.Res.Count + "");
				}
			}

			@Override
			public void onException(
					INetTask<RelationshipGetListRequest, RelationshipGetListResponse> task,
					Exception e) {

			}
		});
		add(rtask);
		DoctorReserveListTask dtask = new DoctorReserveListTask();
		DoctorReserveListRequest dreq = new DoctorReserveListRequest();
		dreq.userid = GlobalSettings.sUid;
		dtask.setRequest(dreq);
		dtask.addListener(new NetTaskListener<DoctorReserveListTask.DoctorReserveListRequest, DoctorReserveListTask.DoctorReserveListResponse>() {

			@Override
			public void onComplete(
					INetTask<DoctorReserveListRequest, DoctorReserveListResponse> task,
					DoctorReserveListResponse response) {
				if (response != null && response.size() > 0) {
					mMyProjectNum.setText(response.size() + "");
				}
			}

			@Override
			public void onException(
					INetTask<DoctorReserveListRequest, DoctorReserveListResponse> task,
					Exception e) {

			}
		});
		add(dtask);
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.view_my_project) {
			Intent i = new Intent(getContext(),
					MyTreatmentProjectListActivity.class);
			startActivity(i);
		} else if (id == R.id.text_right) {
			if (CommonUtility.isNull(view_doctor_qr)) {
				view_doctor_qr = LayoutInflater.from(getContext()).inflate(
						R.layout.view_qr_code, null);
				View ll_qr_code_root = view_doctor_qr
						.findViewById(R.id.ll_qr_code_root);
				ll_qr_code_root.setOnClickListener(this);
				OImageView img_doctor_icon = (OImageView) view_doctor_qr
						.findViewById(R.id.img_doctor_icon);
				QRCodeView img_user_qr_code = (QRCodeView) view_doctor_qr
						.findViewById(R.id.img_user_qr_code);
				TextView text_doctor_id = (TextView) view_doctor_qr
						.findViewById(R.id.text_doctor_id);
				TextView text_doctor_name = (TextView) view_doctor_qr
						.findViewById(R.id.text_doctor_name);
				try {
					text_doctor_name.setText(GlobalSettings.sUser.Name);
					text_doctor_id.setText(GlobalSettings.sUser.Nick);
					// CommonUtility.displayHeadImage(mImage, mBitmapUtils, pic,
					// res, sex);
					/*
					 * mBitmapUtils.display(img_doctor_icon,
					 * GlobalSettings.SERVER_IMG_URL + GlobalSettings.sUser.Pic
					 * + Constant.IMG_TH, new OBitmapLoadCallBack<View>());
					 */
					CommonUtility.displayHeadImage(img_doctor_icon,
							mBitmapUtils, GlobalSettings.SERVER_IMG_URL
									+ GlobalSettings.sUser.Pic
									+ Constant.IMG_TH, getContext()
									.getResources(), GlobalSettings.sUser.Sex);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				JSONObject object = new JSONObject();
				try {
					object.put("Uid", GlobalSettings.sUser.Uid);
					object.put("User_type", GlobalSettings.sUser.User_Type);
					object.put("Method", "Follow.Set.Add");
				} catch (Exception e) {
					e.printStackTrace();
				}
				img_user_qr_code.setText(object.toString());
				mVarcardDialog.setContentView(view_doctor_qr);
			}
			mVarcardDialog.show();
		} else if (id == R.id.ll_qr_code_root) {
			if (mVarcardDialog != null)
				mVarcardDialog.dismiss();
		} else if (id == R.id.rl_profile) {
			startActivity(new Intent(getContext(),
					PatientProfileEditActivity.class));
		} else if (id == R.id.view_yue) {
			startActivity(new Intent(getContext(), AccountActivity.class));
		} else if (id == R.id.view_my_question) {
			startActivity(new Intent(getContext(),
					MyQuestionDetailActivity.class));
		} else if (id == R.id.view_my_guanzhu) {
			String[] values = (String[]) view.getTag();
			Intent intent = new Intent(getContext(),
					MyFollowingDoctorActivity.class);
			intent.putExtra(Constant.mFollowDoctor, true);
			intent.putExtra(Constant.IDENTITY_KEY, true);
			startActivity(intent);
		} else if (id == R.id.view_system_setting) {
			startActivity(new Intent(getContext(), SystemActivity.class));
		} else if (id == R.id.view_tip_msg) {

			Log.i("testmessage", "onClick");

			startActivity(new Intent(getContext(), TipMessageActivity.class));
		} else if (id == R.id.view_my_shoucang) {
			startActivity(new Intent(getContext(),
					MyFollowingQuestionActivity.class));
		} else if (id == R.id.view_my_doctor) {
			Intent intent = new Intent(getContext(),
					MyFollowingDoctorActivity.class);
			intent.putExtra(Constant.IDENTITY_KEY, true);
			intent.putExtra(Constant.mFollowDoctor, false);
			startActivity(intent);
		} else if (id == R.id.add_doctor) {
			Intent intent = new Intent(getContext(), ScanActivity.class);
			startActivityForResult(intent, 0);
		} else if (id == R.id.img_patient_icon) {
			CommonUtility.toPersonHomeActivity(getContext(),
					GlobalSettings.sUser);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		try {
			if (!CommonUtility.isNull(data)) {
				String info = data.getStringExtra(Constant.IDENTITY_KEY);
				JSONObject object = new JSONObject(info);
				final int userType = object.getInt("User_type");
				HashMap<String, Object> params = new HashMap<String, Object>();
				params.put(Constant.PARAM_API, "User.Get");
				params.put("uids", object.getInt("Uid"));
				RequestTaskIntercept.requestIntercept(getContext(),
						Constant.URL.REQUEST, new RequestHandler(getContext(),
								new HandlerCallback() {

									@Override
									public void callback(Object o) {
										if (!CommonUtility.isNull(o)) {
											try {
												JSONObject object = (JSONObject) o;
												JSONArray array = object
														.getJSONArray(Constant.JSON_PARAM_RES);
												if (array.length() > 0) {
													object = array
															.getJSONObject(0);
													if (userType == 2) {
														Intent intent = new Intent(
																getContext(),
																DoctorDetailActivity.class);
														intent.putExtra(
																Constant.IDENTITY_KEY,
																object.toString());
														startActivity(intent);
													} else if (userType == 1) {
														Intent intent = new Intent(
																getContext(),
																QuestionDetailActivity.class);
														intent.putExtra(
																Constant.IDENTITY_KEY,
																object.toString());
														intent.putExtra(
																Constant.IDENTITY_KEY_1,
																true);
														startActivity(intent);
													}
												}
											} catch (Exception e) {
												e.printStackTrace();
											}
										}
									}
								}), params);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
